﻿package
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.utils.getDefinitionByName;
	
	/**
	 * Класс, загружающий основную флешку
	 * @author kasoi (fsca.ru)
	 */
	public class Preloader extends Sprite 
	{
		////////////////////////////////////////////////////////////////////
		// Private properties
		////////////////////////////////////////////////////////////////////
		
		private var swfLoader: Loader;
		
		private var progress: Number = 0;
		
		private var _width: Number = 0.1;
		
		private var isDone: Boolean = false;
		
		////////////////////////////////////////////////////////////////////
		// Public methods
		////////////////////////////////////////////////////////////////////
		
		public function Preloader() 
		{
			this.swfLoader = new Loader();
			var urlRequest: URLRequest = new URLRequest('app.swf');
			//var urlRequest: URLRequest = new URLRequest('http://fsca.ru/flash/test/site.swf?f='+Math.random());
			this.swfLoader.load(urlRequest);
			
			this.swfLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, this.swfLoader_onProgress);
			this.swfLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.swfLoader_onComplete);
			this.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
		}
		
		////////////////////////////////////////////////////////////////////
		// Private methods
		////////////////////////////////////////////////////////////////////
		
		private function startup() : void 
		{
			var content: DisplayObject = this.swfLoader.content;
			this.addChild(content);
		}
		
		////////////////////////////////////////////////////////////////////
		// Listeners
		////////////////////////////////////////////////////////////////////
		
		private function swfLoader_onProgress(e: ProgressEvent) : void 
		{
			//trace(e.bytesLoaded, e.bytesTotal);
			this.progress = e.bytesLoaded / e.bytesTotal;
		}
		
		private function swfLoader_onComplete(e: Event) : void 
		{
			//this.startup();
		}
		
		private function onEnterFrame(e: Event) : void 
		{
			var sw: Number = stage.stageWidth;
			var sh: Number = stage.stageHeight;
			var h: Number = 15;
			var y: Number = sh - h;
			
			var toW: Number = this.progress * sw;
			this._width += (toW - this._width) / 10;
			var w: Number = this._width;
			
			this.graphics.clear();
			this.graphics.beginFill(0x333333, 0.8);
			this.graphics.drawRect(0, y, w, h);
			
			if (w + 2 >= stage.stageWidth) 
			{
				this.graphics.clear();
				this.startup();
			}
		}
	}
	
}